<template>
	<div>
		<el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
			<el-form-item prop="username">
				<el-input v-model="loginForm.username" placeholder="用户名：admin">
					<template #prefix>
						<el-icon class="el-input__icon"><user /></el-icon>
					</template>
				</el-input>
			</el-form-item>
			<el-form-item prop="password">
				<el-input v-model="loginForm.password" type="password" placeholder="密码：123456" show-password autocomplete="new-password">
					<template #prefix>
						<el-icon class="el-input__icon"><lock /></el-icon>
					</template>
				</el-input>
			</el-form-item>
		</el-form>
		<div class="login-btn">
			<!-- <el-button :icon="CircleClose" round size="large" @click="resetForm(loginFormRef)">重置</el-button>
			<el-button :icon="UserFilled" round size="large" type="primary" :loading="loading" @click="login(loginFormRef)"> -->
			<el-button round size="large" @click="resetForm(loginFormRef)">重置</el-button>
			<el-button round size="large" type="primary" :loading="loading" @click="login(loginFormRef)">
				登录
			</el-button>
		</div>
	</div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
// import { CircleClose, UserFilled } from "@element-plus/icons-vue";
import unifiedTip from '@/utils/unifiedTip'// 全局统一提示
const { Notification } = unifiedTip
import { getTimeState } from "@/utils/utils";
import { useRouter } from "vue-router";
import { loginSys } from '@/api/global'
import store from '@/store'

const router = useRouter();

// 定义 formRef（校验规则）
const loginFormRef = ref();
const loginRules = reactive({
	username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
	password: [{ required: true, message: "请输入密码", trigger: "blur" }]
});

const loading = ref(false);
const loginForm = reactive({ username: "", password: "" });
const login = (formEl) => {
	if (!formEl) return;
	formEl.validate(async valid => {
		if (!valid) return;
		loading.value = true;
		try {
			// console.log('loginForm----', loginForm)
			const res = await loginSys({ uname: loginForm.username, pwd: loginForm.password })

			if(res.code === 200 && res.status === 200) {
				store.commit('user/setToken', res.data.token)
				// 4.跳转到首页
				router.push('/learn');
				Notification({
					title: getTimeState(),
					message: "欢迎登录 LaoCheng-Admin",
					type: "success",
					duration: 3000
				});
			} else {
				console.log('login-res-', res)
			}
		} finally {
			loading.value = false;
		}
	});
};

// resetForm
const resetForm = (formEl) => {
	if (!formEl) return;
	formEl.resetFields();
};

onMounted(() => {
	// 监听enter事件（调用登录）
	document.onkeydown = (e) => {
		e = window.event || e;
		if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
			if (loading.value) return;
			login(loginFormRef.value);
		}
	};
});
</script>

<style scoped lang="scss">
@import "../index.scss";
</style>
